package ccnt.pvc.scudwaremobile.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import ccnt.pvc.scudwaremobile.R;
import ccnt.pvc.scudwaremobile.bean.ResultObject;
import ccnt.pvc.scudwaremobile.dao.ApkModel;
import ccnt.pvc.scudwaremobile.dao.ServiceModel;
import ccnt.pvc.scudwaremobile.storage.ApkDbManager;
import ccnt.pvc.scudwaremobile.storage.ServiceDbManager;
import ccnt.pvc.scudwaremobile.utils.Constants;
import ccnt.pvc.scudwaremobile.utils.HttpClientUtils;
import ccnt.pvc.scudwaremobile.utils.JsonUtils;
import ccnt.pvc.scudwaremobile.utils.ThreadPoolUtils;

public class ApkListActivity extends Activity implements OnClickListener {

	private final static String TAG = ApkListActivity.class.getName();
	
	private final static int MESSAGE_ALREADY_NEW = 1;
	private final static int MESSAGE_NO_RESPONSE = 2;
	private final static int MESSAGE_UPDATE_SUCCESS = 3;
	
	ApkDbManager apkDbManager = null;
	ServiceDbManager serviceDbManager = null;
	Button btnUpdate;
	ListView listApk;
	int apkCount = 0;
	List<ApkModel> apkModels = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_apklist);

		initService();
		initView();
	}
	
	@Override
	protected void onRestart() {
		fillListApk();
		super.onRestart();
	}

	private void initService() {
		apkDbManager = new ApkDbManager(ApkListActivity.this);
		serviceDbManager = new ServiceDbManager(ApkListActivity.this);
	}
	
	private void initView() {
		btnUpdate = (Button)findViewById(R.id.btnUpdate);
		btnUpdate.setOnClickListener(this);
		
		listApk = (ListView)findViewById(R.id.listApk);
		fillListApk();
	}
	
	private void fillListApk() {
		apkModels = apkDbManager.getAllApks();
		if(apkModels.size() == 0) {
			Toast.makeText(ApkListActivity.this, "暂无数据，请更新", Toast.LENGTH_SHORT)
					.show();
		}
		
		apkCount = apkModels.size();
		ArrayList<String> infos = new ArrayList<String>();
		for(ApkModel apkModel : apkModels) {
			StringBuilder builder = new StringBuilder();
			builder.append(apkModel.getApkName());
			builder.append("\n");
			builder.append(apkModel.getIsInstalled() == 1 ? "已安装" : "未安装");
			infos.add(builder.toString());
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				ApkListActivity.this, android.R.layout.simple_list_item_1,
				infos);
		listApk.setAdapter(adapter);
		listApk.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String packageName = apkModels.get(arg2).getPackageName();
				Intent intent = new Intent(ApkListActivity.this, ApkDetialActivity.class);
				intent.putExtra("packageName", packageName);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch(id) {
		case R.id.btnUpdate:
			ThreadPoolUtils.execute(new Runnable() {
				
				@Override
				public void run() {
					checkUpdate();
				}
			});
			break;
		}
	}
	
	private void checkUpdate() {
		Map<String, Object> params = new HashMap<String, Object>();
		ResultObject resultObject = HttpClientUtils.sendGet(Constants.SERVER_URL + "/apk/number.do", params);
		int code = resultObject.getCode();
		//int code = 200;
		if(code == 200) {
			
			//resultObject.getResult()得到count;
			int count = 0; 
			try {
				count = Integer.parseInt(resultObject.getResult());
			} catch(Exception e) {
				e.printStackTrace();
			}
			
			if(count <= apkCount) {
				Message msg = Message.obtain(null, MESSAGE_ALREADY_NEW, 0, 0);
				handler.sendMessage(msg);
			} else {
				update(apkCount, count);
			}
		} else {
			Log.e(TAG, "连接服务器出错");
			Message msg = Message.obtain(null, MESSAGE_NO_RESPONSE, 0, 0);
			handler.sendMessage(msg);
			return;
		}
	}
	
	private void update(int localCount, int serverCount) {
		Map<String, Object> params = new HashMap<String, Object>();
		ResultObject resultObject = HttpClientUtils.sendGet(
				Constants.SERVER_URL + "/apk/list.do", params);
		int code = resultObject.getCode();
		if(code == 200) {
			// TODO 插入新的数据
//			ApkModel apkModel = new ApkModel();
//			apkModel.setApkName("weixin");
//			apkModel.setPackageName("com.freedom.weixin");
//			apkModel.setDeveloper("freedom");
//			apkDbManager.insertApk(apkModel);
			
			List<ApkModel> list = JsonUtils.convertToApks(resultObject.getResult());
			List<ApkModel> subList = list.subList(localCount, serverCount);
			apkDbManager.insertApks(subList);
			Log.d(TAG, "insert apk " + subList.size());
			
			// TODO 更新service
			if(!updateService())
				return;
			
			Message msg = Message.obtain(null, MESSAGE_UPDATE_SUCCESS, 0, 0);
			handler.sendMessage(msg);
			
		} else {
			Log.e(TAG, "连接服务器出错");
			Message msg = Message.obtain(null, MESSAGE_NO_RESPONSE, 0, 0);
			handler.sendMessage(msg);
		}
	}
	
	/**
	 * 从服务器更新service信息
	 * @return 是否更新成功
	 */
	private boolean updateService() {
		Map<String, Object> params = new HashMap<String, Object>();
		ResultObject resultObject = HttpClientUtils.sendGet(
				Constants.SERVER_URL + "/service/list.do", params);
		int code = resultObject.getCode();
		if(code == 200) {
			List<ServiceModel> list = JsonUtils.convertToServices(resultObject.getResult());
			int serverCount = list.size();
			int localCount = serviceDbManager.getAllServiceCount();
			List<ServiceModel> subList = list.subList(localCount, serverCount);
			serviceDbManager.insertServicesToAll(subList);
			Log.d(TAG, "insert services " + subList.size());
			return true;
		} else {
			Log.e(TAG, "连接服务器出错");
			Message msg = Message.obtain(null, MESSAGE_NO_RESPONSE, 0, 0);
			handler.sendMessage(msg);
			return false;
		}
	}
	
	private final Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MESSAGE_ALREADY_NEW:
				Toast.makeText(ApkListActivity.this, "数据已经是最新的", Toast.LENGTH_SHORT)
					.show();
				break;
			case MESSAGE_NO_RESPONSE:
				Toast.makeText(ApkListActivity.this, "无响应", Toast.LENGTH_SHORT)
					.show();
				break;
			case MESSAGE_UPDATE_SUCCESS:
				Toast.makeText(ApkListActivity.this, "更新成功", Toast.LENGTH_SHORT)
					.show();
				fillListApk();
				break;
			}
		}
		
	};
}
